package com.wfyn.reggie.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wfyn.reggie.common.web.exception.base.BusinessException;
import com.wfyn.reggie.modules.sys.domain.Setmeal;
import com.wfyn.reggie.modules.sys.domain.SetmealDish;
import com.wfyn.reggie.modules.sys.param.SetmealDto;
import com.wfyn.reggie.modules.sys.service.SetmealDishService;
import com.wfyn.reggie.modules.sys.service.SetmealService;
import com.wfyn.reggie.modules.sys.mapper.SetmealMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author wfyn
* @description 针对表【setmeal(套餐)】的数据库操作Service实现
* @createDate 2023-09-25 15:59:00
*/
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal>
    implements SetmealService{

    @Autowired
    SetmealDishService setmealDishService;
    @Autowired
    SetmealMapper setmealMapper;

    @Override
    @Transactional
    public void saveSetmealDto(SetmealDto setmealDto) {
        //保存套餐的进本信息，操作setmeal,执行insert操作
        this.save(setmealDto);

        List<SetmealDish> collect = setmealDto.getSetmealDishes().stream().map(
                (item) ->
                {
                    item.setSetmealId(setmealDto.getId());
                    return item;
                }

        ).collect(Collectors.toList());
        //保存套餐和菜品的关联信息，操作setmeal_Dish
        setmealDishService.saveBatch(collect);


    }

    @Override
    public void updateStatus(Integer status, List<Long> ids) {

      setmealMapper.updateStatusById(status,ids);

    }

    @Override
    public void deleteSetmealDto(List<Long> ids) {

        int count = this.count(new LambdaQueryWrapper<Setmeal>()
                .in(Setmeal::getId, ids)
                .eq(Setmeal::getStatus, 1));
        //如果不能删除，抛出业务异常
        if (count>0)
        {
            throw new BusinessException("套餐正在售卖中，不能删除");
        }
        //如果可以删除，先删除套餐--setmeal
        this.removeByIds(ids);
        //删除关系表中的数据--setmeal--dish
        setmealDishService.remove(new LambdaQueryWrapper<SetmealDish>()
                .in(SetmealDish::getSetmealId,ids));


    }
}




